package com.keqiang.chart.base

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.keqiang.chart.utils.ObjectPool
import com.keqiang.chart.utils.isInEditMode2

/**
 * 图表[View]基类
 *
 * @author Created by wanggaowan on 2022/10/27 13:15
 */
abstract class BaseChartView<C : IChart<*>> @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    init {
        isInEditMode2 = isInEditMode
    }

    abstract val chart: C

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        chart.draw(canvas)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.pointerCount > 1) {
            return super.onTouchEvent(event)
        }

        if ((chart.animator?.getProgress() ?: 1f) < 1f) {
            // 执行动画的过程不允许触摸
            return super.onTouchEvent(event)
        }

        val touchHandler = chart.touchHandler ?: return super.onTouchEvent(event)
        return touchHandler.onTouch(event) || super.onTouchEvent(event)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        ObjectPool.release()
    }
}